package com.zlsy.learning.leetcode.stack.s496;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @author zhouliang
 * @date 2020/8/12 15:14
 *
 * 栈+hashMap
 * 时间复杂度：
 * 空间复杂度：
 */
public class NextGreaterElement {
  public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
    Stack<Integer> stack = new Stack<>();
    int a = nums1.length;
    while (a > 0) {
      stack.push(nums1[a - 1]);
      a--;
    }
    Map<Integer, Integer> map = new HashMap<>(nums2.length);
    for (int i = 0; i < nums2.length; i++) {
      map.put(nums2[i], i);
    }
    int k = 0;
    int[] result = new int[nums1.length];
    while (!stack.isEmpty()) {
      Integer pop = stack.pop();
      Integer index = map.get(pop);
      if (index + 1 == nums2.length) {
        result[k] = -1;
      } else {
        for (int i = index + 1; i < nums2.length; i++) {
          int v = nums2[i];
          if (v > pop) {
            result[k] = v;
            break;
          } else {
            result[k] = -1;
          }
        }
      }
      k++;
    }
    return result;
  }

  public static void main(String[] args) {
    //      nums1 = [4,1,2], nums2 = [1,3,4,2];
    int[] nums1 = new int[] {4, 1, 2};
    int[] nums2 = new int[] {1, 3, 4, 2};
    int[] ints = nextGreaterElement(nums1, nums2);
    System.out.println(ints);
  }
}
